// src/stores/shopStore.js
import { defineStore } from 'pinia'

export const useShopStore = defineStore('shop', {
    state: () => ({
        goodsList: JSON.parse(localStorage.getItem('goodsList') || '[]'),
        currentUser: JSON.parse(localStorage.getItem('currentUser') || null)
    }),
    actions: {
        // 设置当前用户
        setCurrentUser(user) {
            this.currentUser = user
            localStorage.setItem('currentUser', JSON.stringify(user))
            this.saveToLocalStorage()
        },

        // 获取当前用户的商品列表
        getCurrentUserGoods() {
            if (!this.currentUser) return []
            return this.goodsList.filter(item => item.userId === this.currentUser.id)
        },

        addGoods(goods) {
            // 添加用户ID到商品
            const newGoods = {
                ...goods,
                userId: this.currentUser.id
            }
            this.goodsList.unshift(newGoods)
            this.saveToLocalStorage()
        },

        updateGoods(goods) {
            // 检查商品是否属于当前用户
            if (goods.userId !== this.currentUser.id) {
                throw new Error('无权修改其他用户的商品')
            }

            const index = this.goodsList.findIndex(item => item.id === goods.id)
            if (index !== -1) {
                this.goodsList[index] = goods
                this.saveToLocalStorage()
            }
        },

        deleteGoods(id) {
            // 检查商品是否属于当前用户
            const goods = this.goodsList.find(item => item.id === id)
            if (!goods || goods.userId !== this.currentUser.id) {
                throw new Error('无权删除其他用户的商品')
            }

            this.goodsList = this.goodsList.filter(item => item.id !== id)
            this.saveToLocalStorage()
        },

        saveToLocalStorage() {
            localStorage.setItem('goodsList', JSON.stringify(this.goodsList))
        },
    },
})